package model.hospital;

import net.passClass.PassBuildings;
import net.passClass.PassData;

import java.util.ArrayList;
import java.util.TreeSet;

public class BuildingDB {
    private TreeSet<Building> buildings = new TreeSet<>();

    public TreeSet<Building> getBuildings() {
        return buildings;
    }
    private static BuildingDB instance = null;
    private BuildingDB() {}
    private BuildingDB(TreeSet<Building> buildings) {
        if(buildings!=null){
            this.buildings = buildings;
        } else {
            this.buildings = new TreeSet<>();
        }
    }
    public static BuildingDB getInstance() {
        if (instance == null){
            instance = new BuildingDB();
        }
        return instance;
    }
    public static void initialize(TreeSet<Building> buildings) {
        if (instance == null){
            instance = new BuildingDB(buildings);
        }
    }


    public PassData add(Room room) {
        Building aBuilding = new Building(room.getLocation().getBuildingNumber());
        if(room.getLocation().getFloorNumber()==0){
            if(buildings.contains(aBuilding)) {
                return new PassData(false,null,"建筑已存在，新增失败");
            }
            buildings.add(aBuilding);
            return new PassData(true,null,"建筑新增成功");
        }
        if(!buildings.contains(aBuilding)) {//不能直接add，因为会覆盖而不是忽略
            buildings.add(aBuilding);
        }
        return buildings.ceiling(aBuilding).add(room);
    }

    public PassData delete(Room room) {
        Building aBuilding = new Building(room.getLocation().getBuildingNumber());
        Building theBuilding = buildings.ceiling(aBuilding);
        if(!buildings.contains(theBuilding)){
            return new PassData(false,null,"建筑不存在，删除失败");
        }
        if (room.getLocation().getFloorNumber()==0){     //即删除建筑
            if(!theBuilding.getFloors().isEmpty()){
                return new PassData(false,null,"建筑中存在楼层，删除失败");
            }
            buildings.remove(theBuilding);
            return new PassData(true,null,"建筑删除成功");
        }

        return theBuilding.delete(room);        //删除建筑内对象

    }

    public PassBuildings get() {
        return new PassBuildings(true,buildings,"所有房间获取成功");        //删除建筑内对象

    }

}
